import { onMounted } from 'vue';
<template>
  <dialog
    ref="dialog"
    role="dialog"
    class="max-w-sm min-w-64 border shadow rounded"
  >
    <!-- header -->
    <div class="flex justify-between items-center h-12 box-border px-3 py-2">
      <!-- title -->
      <div>{{ title }}</div>
      <!-- action -->
      <div v-if="closeButton">
        <button
          class="border rounded px-2 bg-base-200 hover:bg-base-300 active:scale-90"
          @click="hide"
        >
          X
        </button>
      </div>
    </div>
    <!-- 分割线 -->
    <div class="border"></div>
    <!-- body -->
    <div
      class="flex flex-col w-full box-border px-3 py-2"
      :class="{
        'justify-center': contentCenter,
      }"
    >
      <slot></slot>
      <slot name="content"></slot>
    </div>
  </dialog>
</template>

<script>
  export default {
    mounted() {
      window.addEventListener("keydown", (e) => {
        if (e.key === "Escape") {
          if (this.$refs.dialog.open) {
            e.preventDefault();
          }
        }
      });
    },

    props: {
      title: {
        type: String,
        default: "标题",
      },
      closeButton: {
        type: Boolean,
        default: true,
      },
      contentCenter: {
        type: Boolean,
        default: false,
      }
    },

    methods: {
      show() {
        if (this.$refs.dialog.open) {
          return;
        }
        this.$refs.dialog.showModal();
        this.$emit("show");
      },
      hide() {
        if (!this.$refs.dialog.open) {
          return;
        }
        this.$refs.dialog.close();
        this.$emit("hide");
      },
      toggle() {
        if (this.$refs.dialog.open) {
          this.show();
        } else {
          this.hide();
        }
        this.$emit("toggle", this.$refs.dialog.open)
      },
    },
  };
</script>
